//
//  addMoneyViewController.m
//  忘不了
//
//  Created by rimi on 16/7/10.
//  Copyright © 2016年 handuan. All rights reserved.
//

#import "addMoneyViewController.h"
#import "SDAutoLayout.h"
#import "UIColor+Expand.h"
#import "UserModel.h"
#import "MBProgressHUD.h"
#import "BaseRequest+MoneyAndRemember.h"
#import "CheckWeb.h"
@interface addMoneyViewController ()<UITextFieldDelegate>
@property (nonatomic,strong)NSDictionary *dic;//存储数据字典
@property (nonatomic,strong)NSMutableArray *dataArr;//存储数据字典的数组
@property (nonatomic,strong)UIView *dateView;//选择日期
@property (nonatomic,strong)UIView *flagView;//设置标签
@end

@implementation addMoneyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
   self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"完成" style:UIBarButtonItemStylePlain target:self action:@selector(finishButtonTaped)];
    
    [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60)
                                                         forBarMetrics:UIBarMetricsDefault];//隐藏导航栏返回按钮自带的文字
    self.title = @"增加开支";
    
    UIImageView *backGroudView = [[UIImageView alloc]initWithFrame:self.view.frame];
    backGroudView.image = [UIImage imageNamed:@"s.jpg"];
    [self.view addSubview:backGroudView];
    
    [self initInterface];
    
}

- (void)initInterface {
    NSArray *Arr1 = @[@"标题",@"金额",@"日期",@"详情",@"地点",@"标签"];
    NSArray *Arr2 = @[@"十五字以内",@"输入金额",@"选择日期",@"输入详情",@"输入地点",@"选择个性标签"];
    NSArray *Arr3 = @[@"勤俭节约",@"一般开销",@"小嗨一把",@"心疼钱包",@"又要吃土",@"奢侈不停",@"土豪日常",@"富可敌国"];
    
    for (int i=0; i<6; i++) {
        UILabel *label = [[UILabel alloc]init];
        label.text = Arr1[i];
        label.textColor = [UIColor whiteColor];
        label.textAlignment = NSTextAlignmentCenter;
        label.font = [UIFont systemFontOfSize:18];
        label.backgroundColor = [UIColor colorWithRed:0.1647 green:0.1647 blue:0.2314 alpha:1.0];
        label.tag = 100 + i;
        label.layer.cornerRadius = 15;
        label.layer.masksToBounds = YES;
        [self.view addSubview:label];
        label.sd_layout
        .widthRatioToView(self.view,0.2)
        .heightIs(self.view.frame.size.width*0.1)
        .leftSpaceToView(self.view,0)
        .topSpaceToView(self.view,64+self.view.frame.size.width*0.1*i+self.view.frame.size.width*0.1*i);
    }
    for (int j=0; j<6; j++) {
        UITextField *textField = [[UITextField alloc]init];
        textField.backgroundColor = [UIColor colorWithRed:0.8588 green:0.8314 blue:0.7725 alpha:1.0];
        textField.textAlignment = NSTextAlignmentCenter;
        textField.placeholder = Arr2[j];
        textField.textColor = [UIColor colorWithRed:0.1647 green:0.1647 blue:0.2314 alpha:1.0];
        textField.font = [UIFont systemFontOfSize:18];
        textField.tag = 200 + j;
        textField.delegate = self;
        textField.layer.cornerRadius = 15;
        textField.layer.masksToBounds = YES;
        [self.view addSubview:textField];
        textField.sd_layout
        .widthRatioToView(self.view,0.4)
        .heightIs(self.view.frame.size.width*0.1)
        .leftSpaceToView(self.view,self.view.frame.size.width*0.2)
        .topEqualToView([self.view viewWithTag:100+j]);
        if (textField.tag == 202) {
            NSString *currentDate = [NSString stringWithFormat:@"%@",[NSDate date]];
            textField.text = [currentDate substringWithRange:NSMakeRange(0,10)];
        }
    }
    
    _flagView = [[UIView alloc]init];
    _flagView.alpha = 0;
    _flagView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_flagView];
    _flagView.sd_layout
    .leftSpaceToView(self.view,0)
    .rightSpaceToView(self.view,0)
    .bottomSpaceToView([self.view viewWithTag:205],0)
    .heightIs(self.view.frame.size.width*0.5);
    
    for (int m=0; m<8; m++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        [button setTitle:Arr3[m] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor colorWithRed:0.1216 green:0.1216 blue:0.1765 alpha:1.0] forState:UIControlStateNormal];
        button.backgroundColor = [UIColor colorWithRed:0.8275 green:0.7961 blue:0.7216 alpha:1.0];
        button.tag = 300 + m;
        button.layer.cornerRadius = 15;
        button.layer.masksToBounds = YES;
        [button addTarget:self action:@selector(flagButtonTaped:) forControlEvents:UIControlEventTouchUpInside];
        [self.flagView addSubview:button];
        if (button.tag < 304) {
            button.sd_layout
            .widthRatioToView(self.view,0.2)
            .heightIs(self.view.frame.size.width*0.1)
            .leftSpaceToView(self.flagView,15*(m+1)+self.view.frame.size.width*0.2*m)
            .bottomSpaceToView(self.flagView,self.view.frame.size.width*0.3);
        } else {
            button.sd_layout
            .widthRatioToView(self.view,0.2)
            .heightIs(self.view.frame.size.width*0.1)
            .leftSpaceToView(self.flagView,15*(m-4+1)+self.view.frame.size.width*0.2*(m-4))
            .bottomSpaceToView(self.flagView,self.view.frame.size.width*0.1);
        }
    }
    
    _dateView = [[UIView alloc]init];
    _dateView.backgroundColor = [UIColor colorWithRed:0.8275 green:0.7961 blue:0.7216 alpha:1.0];
    _dateView.alpha = 0;
    _dateView.layer.cornerRadius = 15;
    _dateView.layer.masksToBounds = YES;
    [self.view addSubview:_dateView];
    _dateView.sd_layout
    .leftSpaceToView(self.view,self.view.frame.size.width*0.2)
    .rightSpaceToView(self.view,10)
    .topEqualToView([self.view viewWithTag:202])
    .heightIs(self.view.frame.size.width*0.5);
    
    UIDatePicker *datePicker = [[UIDatePicker alloc]init];
    datePicker.datePickerMode = UIDatePickerModeDate;
    datePicker.minuteInterval = 1;
    //时间范围
    NSDate *minDate = [[NSDate alloc]initWithTimeIntervalSince1970:5];
    //最小时间
    datePicker.minimumDate = minDate;
    //语言
    datePicker.locale = [[NSLocale alloc]initWithLocaleIdentifier:@"zh_CN"];
    //日历(默认当天)
    datePicker.calendar = [NSCalendar currentCalendar];
    //时区
    datePicker.timeZone = [NSTimeZone localTimeZone];
    [datePicker addTarget:self action:@selector(dateChanged:) forControlEvents:UIControlEventValueChanged];
    [self.dateView addSubview:datePicker];
}

//时间改变
-(void)dateChanged:(UIDatePicker *)sender{
    NSDateFormatter *dateformatter = [[NSDateFormatter alloc]init];
    [dateformatter setDateFormat:@"yyyy-MM-dd"];
    NSString *dateStr = [dateformatter stringFromDate:sender.date];
    NSLog(@"选中的日期%@",dateStr);
    
    UITextField *date = [self.view viewWithTag:202];
    date.text = [NSString stringWithFormat:@"%@",dateStr];
}

- (void)flagButtonTaped:(UIButton *)sender {
    NSString *flagText = sender.titleLabel.text;
    UITextField *flagTextField = [self.view viewWithTag:205];
    flagTextField.text = flagText;
}

- (void)finishButtonTaped {
    UITextField *title = [self.view viewWithTag:200];
    UITextField *money = [self.view viewWithTag:201];
    UITextField *date = [self.view viewWithTag:202];
    UITextField *detail = [self.view viewWithTag:203];
    UITextField *address = [self.view viewWithTag:204];
    UITextField *flag = [self.view viewWithTag:205];

    if ([title.text isEqual:@""] || [money.text isEqual:@""] || [date.text isEqual:@""] || [detail.text isEqual:@""] || [address.text isEqual:@""] || [flag.text isEqual:@""]) {
        UIAlertController *tips = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请输入完整" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
        [tips addAction:sure];
        [self presentViewController:tips animated:YES completion:nil];
    } else if([money.text integerValue] == 0 || [money.text integerValue] < 0){
        UIAlertController *tip = [UIAlertController alertControllerWithTitle:@"提示" message:@"金额输入有误" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *sureButton = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
        [tip addAction:sureButton];
        [self presentViewController:tip animated:YES completion:nil];
    } else {
        _dic = [NSDictionary dictionary];
        _dic = @{@"title":title.text,@"money":money.text,@"date":date.text,@"detail":detail.text,@"address":address.text,@"flag":flag.text};
        _dataArr = [NSMutableArray array];
        [_dataArr addObject:_dic];
        
        UserModel *user = [UserModel shareUserModel];
        if (user.isLogin) {
            [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            //如果登陆，存到网上
            [BaseRequest startUpDataSourceWithFormName:@"Money" dataSource:@[_dic] completionhanlder:^(Response *response) {
                if (response.isSuccess) {
                   [self.navigationController popViewControllerAnimated:YES];
                } else {
                    UIAlertController *tip = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请检查当前网络" preferredStyle:UIAlertControllerStyleAlert];
                    [self presentViewController:tip animated:YES completion:nil];
                    [self performSelector:@selector(dismiss) withObject:nil afterDelay:1.5];
                }
            }];
        }
    }
}

//dismiss 警告提示框
- (void)dismiss
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

// textField代理方法，实现动态改变布局
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    NSInteger n = textField.tag-200;
    if (n == 0 || n == 1 || n == 3 || n == 4) {
       textField.sd_resetLayout
        .widthRatioToView(self.view,0.8)
        .heightIs(self.view.frame.size.width*0.1)
        .leftSpaceToView(self.view,self.view.frame.size.width*0.2)
        .topEqualToView([self.view viewWithTag:100+n]);
    }
    if (n == 2) {
        _dateView.alpha = 1;
    }
    if (n == 5) {
        textField.userInteractionEnabled = NO;
        _flagView.alpha = 1;
        for (int k=0; k<6; k++) {
            if (k != 5) {
                [self.view viewWithTag:100+k].hidden = YES;
                [self.view viewWithTag:200+k].hidden = YES;
            }
        }
        
    }
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    NSInteger n = textField.tag-200;
    if (n == 0 || n == 1 || n == 3 || n == 4) {
        CGFloat width = [self widthForString:textField.text fontSize:18 andHeight:self.view.frame.size.width*0.1];
        textField.sd_resetLayout
        .widthIs(width)
        .heightIs(self.view.frame.size.width*0.1)
        .leftSpaceToView(self.view,self.view.frame.size.width*0.2)
        .topEqualToView([self.view viewWithTag:100+n])
        .maxWidthIs(self.view.frame.size.width*0.8)//最大宽度
        .minWidthIs(self.view.frame.size.width*0.4);//最小宽度
    }
    if (n == 2) {
        _dateView.alpha = 0;
    }
    if (n == 5) {
        textField.userInteractionEnabled = YES;
        _flagView.alpha = 0;
        for (int x=0; x<6; x++) {
            [self.view viewWithTag:100+x].hidden = NO;
            [self.view viewWithTag:200+x].hidden = NO;
        }
    }
}

//判断字符的长度
-(CGFloat) widthForString:(NSString *)value fontSize:(CGFloat)fontSize andHeight:(CGFloat)height
{
    CGSize sizeToFit = [value sizeWithFont:[UIFont systemFontOfSize:fontSize] constrainedToSize:CGSizeMake(CGFLOAT_MAX, height) lineBreakMode:NSLineBreakByWordWrapping];//此处的换行类型（lineBreakMode）可根据自己的实际情况进行设置
    return sizeToFit.width;
}

//触摸收回
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    _dateView.alpha = 0;
    _flagView.alpha = 0;
    [self textFieldDidEndEditing:[self.view viewWithTag:200]];
    [self textFieldDidEndEditing:[self.view viewWithTag:201]];
    [self textFieldDidEndEditing:[self.view viewWithTag:202]];
    [self textFieldDidEndEditing:[self.view viewWithTag:203]];
    [self textFieldDidEndEditing:[self.view viewWithTag:204]];
    [self textFieldDidEndEditing:[self.view viewWithTag:205]];
    
    [self.view endEditing:YES];
}

//UITextField 文本框只能输入数字，且保留2位小数的实现、限定文本长度
- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    //文本框限定最大长度
    if (textField == [self.view viewWithTag:200]) {
        if (range.location >= 15) {
            return NO;
        }
        return YES;
    }
    if (textField == [self.view viewWithTag:201]) {
        NSScanner *scanner = [NSScanner scannerWithString:string];
        NSCharacterSet *numbers;
        NSRange pointRange = [textField.text rangeOfString:@"."];
        if ((pointRange.length > 0) && (pointRange.location < range.location || pointRange.location > range.location + range.length))
        {
            numbers = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
        }
        else
        {
            numbers = [NSCharacterSet characterSetWithCharactersInString:@"0123456789."];
        }
        if ([textField.text isEqualToString:@""] && [string isEqualToString:@"."])
        {
            return NO;
        }
        short remain = 2; //默认保留2位小数
        NSString *tempStr = [textField.text stringByAppendingString:string];
        NSUInteger strlen = [tempStr length];
        if(pointRange.length > 0 && pointRange.location > 0){ //判断输入框内是否含有“.”。
            if([string isEqualToString:@"."]){ //当输入框内已经含有“.”时，如果再输入“.”则被视为无效。
                return NO;
            }
            if(strlen > 0 && (strlen - pointRange.location) > remain+1){ //当输入框内已经含有“.”，当字符串长度减去小数点前面的字符串长度大于需要要保留的小数点位数，则视当次输入无效。
                return NO;
            }
        }
        NSRange zeroRange = [textField.text rangeOfString:@"0"];
        if(zeroRange.length == 1 && zeroRange.location == 0){ //判断输入框第一个字符是否为“0”
            if(![string isEqualToString:@"0"] && ![string isEqualToString:@"."] && [textField.text length] == 1){ //当输入框只有一个字符并且字符为“0”时，再输入不为“0”或者“.”的字符时，则将此输入替换输入框的这唯一字符。
                textField.text = string;
                return NO;
            }else{
                if(pointRange.length == 0 && pointRange.location > 0){ //当输入框第一个字符为“0”时，并且没有“.”字符时，如果当此输入的字符为“0”，则视当此输入无效。
                    if([string isEqualToString:@"0"]){
                        return NO;
                    }
                }
            }
        }
        NSString *buffer;
        if ( ![scanner scanCharactersFromSet:numbers intoString:&buffer] && ([string length] != 0) )
        {
            return NO;
        }
    }
    return YES;
}


@end
